package com.tienon.message.mq;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ibm.mq.MQException;
import com.tienon.message.entity.Push_App;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MQSendAppMsgTask {

	private static Logger log = Logger.getLogger(MQSendAppMsgTask.class);

	@Resource
	private GetTenAppMsgNeedReSend getReSendAppMsg;

	@Resource
	private SendDataToMQ sendDataToMQ;
	@Resource
	private GetTenAppMsgsAndUpdateState getAppMsg;
	// 因为是原生模式不是单例模式，所以最好为静态的
	public static Long delay = 1L;

	// 用于调节延时的
	private Object objWait = new Object();

	// 记录发送条数用于重发
	private static int line = 0;

	public void sendTenDatasToMQ() throws MQException, IOException,
			InterruptedException {

		// 不要让datas为null，否则后面调用方法会有空指针异常
		List<Push_App> datas = new ArrayList<Push_App>();

		line++;
		/**
		 * 当数据发了1000次的时候，检验数据是否有需要重发的。 用“>=”因为直接的“=”号，每个线程绕过了1000，就永远不能执行，if中的代码
		 */
		if (line >= 1000) {
			line = 1;
			delay++;
			log.info("重发: 线程:" + Thread.currentThread().getName()
					+ " 进入，准备重发10条数据d到MQ.");
			datas = getReSendAppMsg.getTenNeedReSendAppMsg();
		} else {
			log.info("线程:" + Thread.currentThread().getName()
					+ " 进入，准备发送10条数据到MQ.");
			// 无论如何都会返回实例list对象，即不为null
			// 所以最好判断list的size 大小
			datas = getAppMsg.getTenAppMsgsAndUpdateState();
			// System.out.println(datas);
		}

		valdateAppMsgOrDelay(datas);

		// if (sendDataToMQ.isMQNull()
		// || !sendDataToMQ.isManagerConnectedAndOpen()) {
		sendDataToMQ.openMQ();
		// }
		for (Push_App data : datas) {
			sendDataToMQ.sendMsg(data);
			log.info("线程:" + Thread.currentThread().getName()
					+ " 已经发送数据到MQ，数据内容是: " + " 批次号:" + data.getBatId()
					+ " 流水号:" + data.getSerial() + " 序号:" + data.getSplitId()
					+ " 消息的优先级:" + data.getPrior() + " 发送时间:"
					+ data.getSendTime() + " 内容:" + data.getMsg());

		}
		// sendDataToMQ.commit();
		// sendDataToMQ.closeMQ();

	}

	public void valdateAppMsgOrDelay(List<Push_App> datas)
			throws InterruptedException {
		if (datas.size() > 0) {
			delay = 1L;
		} else {
			synchronized (objWait) {

				if (datas.size() == 0 && delay <= 3) {// 取到空，就是开始重发
					line = 1000;

				} else {

					delay += 300;
					log.info("线程:" + Thread.currentThread().getName()
							+ " 预计延时:" + delay + "ms");
					objWait.wait(delay);
				}

				// System.out.println("51:"+delay);
			}
		}
	}

}
